<template>
    <div class="user-container">
        <el-card shadow="never">
            <template slot="header">
                <span>用户列表</span>
            </template>
            <div class="clearfix">
                <el-form :inline="true" class="search-form">
                    <el-form-item label="用户姓名">
                        <el-input placeholder="请输入用户姓名" v-model="listQuery.userName" clearable />
                    </el-form-item>
                    <el-form-item label="用户手机号">
                        <el-input placeholder="请输入用户手机号" v-model="listQuery.userPhone" clearable />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                        <el-button @click="reset" icon="el-icon-refresh-right">重置</el-button>
                        <el-button type="primary" icon="el-icon-plus" @click="handleCreate"
                            v-auth="'add'">添加用户</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-table v-loading="listLoading" element-loading-text="数据正在加载中" :data="tableList" border fit
                highlight-current-row style="width: 100%">
                <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
                    :align="item.align" :width="item.width">

                    <template slot-scope="{ row, $index  }">
                        <div v-if="item.prop === 'index'">{{ $index + 1 }}</div>
                        <div v-else-if="item.prop === 'userStatus'">
                            <el-tag :type="row.userStatus == 'NORMAL' ? 'success' : 'danger'">
                                {{ row.userStatus == 'NORMAL' ? '启用' : '禁用' }}
                            </el-tag>
                        </div>
                        <div v-else>{{ row[item.prop] }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="330">
                    <template slot-scope="{ row }">
                        <el-button :type="row.userStatus == 'NORMAL' ? 'danger' : 'success'" size="mini"
                            @click="handleStatusChange(row)">
                            {{ row.userStatus == 'NORMAL' ? '禁用' : '启用' }}
                        </el-button>
                        <el-button type="primary" size="mini" @click="handleEdit(row)" v-auth="'edit'">编辑</el-button>
                        <el-button type="primary" size="mini" @click="handleEditPassword(row)" v-auth="'edit'">修改密码</el-button>
                        <!-- 分配角色 -->
                        <el-button type="primary" size="mini" @click="handleAssignRole(row)" v-auth="'assignRole'">分配角色</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <Pagination v-if="total > 0" :total="total" :page.sync="listQuery.current" :page_size="listQuery.size"
                @pagination="getList" />
        </el-card>
        <el-dialog :visible.sync="isShowUpdateModal" :before-close="cancelConfirm" append-to-body destroy-on-close
            :title="dialogTitle" width="60%" :close-on-click-modal="false">
            <el-form :model="adminForm" :rules="adminRules" label-width="80px" ref="formRef">
                <el-form-item label="姓名" prop="userName">
                    <el-input type="text" v-model="adminForm.userName" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="手机号码" prop="userPhone">
                    <el-input type="text" maxlength="11" v-model="adminForm.userPhone" placeholder="请输入手机号码"></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="userIdNo">
                    <el-input type="text" v-model="adminForm.userIdNo" placeholder="请输入身份证号"></el-input>
                </el-form-item>
                <el-form-item label="登录密码" prop="password" v-if="dialogTitle === '新增'">
                    <el-input type="text" v-model="adminForm.password" placeholder="请输入登录密码"></el-input>
                </el-form-item>
                <el-form-item label="部门名称" prop="deptId">
                    <el-select v-model="adminForm.deptId" placeholder="请选择部门" clearable filterable
                        @change="handleDeptChange" style="width: 100%">
                        <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName"
                            :value="item.deptId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input type="text" v-model="adminForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelConfirm()"> 取消 </el-button>
                <el-button type="primary" @click="handleConfirm()"> 确认 </el-button>
            </div>
        </el-dialog>
        <!-- 修改密码 -->
        <el-dialog :visible.sync="isShowEditPasswordModal" :before-close="cancelConfirm" append-to-body destroy-on-close
            :title="dialogTitle" width="40%" :close-on-click-modal="false">
            <el-form :model="passwordForm" :rules="passwordRules" label-width="80px" ref="passwordFormRef">
                <el-form-item label="旧密码" prop="oldPassword">
                    <el-input type="text" v-model="passwordForm.oldPassword" placeholder="请输入旧密码"></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                    <el-input type="text" v-model="passwordForm.newPassword" placeholder="请输入新密码"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelEditPasswordConfirm()"> 取消 </el-button>
                <el-button type="primary" @click="handleEditPasswordConfirm()"> 确认 </el-button>
            </div>
        </el-dialog>

        <!-- 分配角色 -->
        <el-dialog :visible.sync="isShowAssignRoleModal" :before-close="cancelAssignRole" append-to-body
            destroy-on-close title="分配角色" width="50%" :close-on-click-modal="false">
            <el-form label-width="80px">
                <el-form-item label="用户姓名:">
                    <span>{{ currentUser.userName }}</span>
                </el-form-item>
                <el-form-item label="选择角色:">
                    <div class="role-selection-container">
                        <div class="role-selection-container-title">
                            请选择要分配给该用户的角色（可多选）
                        </div>
                        <el-checkbox-group v-model="selectedRoleIds">
                            <el-checkbox v-for="role in roleOptions" :key="role.roleId" :label="role.roleId"
                                :disabled="role.disabled" class="role-checkbox">
                                {{ role.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                        <div v-if="roleOptions.length === 0" class="role-selection-tip">
                            暂无可用角色，请先创建角色
                        </div>
                        <div v-else-if="selectedRoleIds.length === 0" class="role-selection-tip"
                            style="color: #E6A23C;">
                            请至少选择一个角色
                        </div>
                        <div v-else class="role-selection-tip" style="color: #67C23A;">
                            已选择 {{ selectedRoleIds.length }} 个角色
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancelAssignRole()" :disabled="assignRoleLoading"> 取消 </el-button>
                <el-button type="primary" @click="handleAssignRoleConfirm()" :loading="assignRoleLoading"> 确认
                </el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { getAdministratorList, addAdministratorItem, editAdministratorItem, updateUserStatus, updateUserPassword, assignUserRoles, getRoleListByUserId } from '../api/user';
import { getDeptTree } from '../api/department';
import { roleList } from '../api/role';
import Pagination from '@/components/Pagination.vue';
const default_form = {
    userName: '',
    userPhone: '',
    userIdNo: '',
    password: '',
    deptId: '',
    email: ''
};
export default {
    name: 'UserList',
    components: { Pagination },
    filters: {
        statusFilter(status) {
            const statusMap = {
                active: 'success',
                inactive: 'info',
                deleted: 'danger'
            };
            return statusMap[status];
        }
    },
    data() {
        // 密码
        const validatePass = (rule, value, callback) => {
            if (value && value.length > 0 && value.length < 6) {
                callback(new Error("请输入6-16位密码"));
            } else {
                callback();
            }
        };
        const validateUsername = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入用户姓名'));
            } else {
                callback();
            }
            // const reg = /^[a-zA-Z0-9_-]+$/;
            // if (!reg.test(value)) {
            //     callback(new Error("用户名只能包含字母、数字、下划线和破折号"));
            // } else {
            //     callback()
            // }
        };
        //
        const validateEmail = (rule, value, callback) => {
            if (!value || value.length === 0) {
                callback(); // 邮箱为空时通过验证（因为不是必填）
            } else {
                const reg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
                if (!reg.test(value)) {
                    callback(new Error("邮箱格式不正确"));
                } else {
                    callback();
                }
            }
        };
        return {
            isShowEditPasswordModal: false,
            passwordForm: {
                oldPassword: '',
                newPassword: ''
            },
            passwordRules: {
                oldPassword: [
                    { required: true, message: '请输入旧密码', trigger: 'blur' }
                ],
                newPassword: [
                    { required: true, validator: validatePass, trigger: 'blur' }
                ]
            },
            deptList: [],
            deptOptions: [],
            roleOptions: [],
            currentData: null,
            dialogTitle: '',
            adminForm: { ...default_form },
            adminRules: {
                userName: [
                    { required: true, validator: validateUsername, trigger: 'blur' }
                ],
                userPhone: [
                    { required: true, message: '请输入手机号码', trigger: 'blur' }
                ],
                password: [
                    { required: true, validator: validatePass, trigger: 'blur' }
                ],
                userIdNo: [
                    { required: true, message: '请输入身份证号', trigger: 'blur' }
                ],
                deptId: [
                    { required: false, message: '请选择部门', trigger: 'change' }
                ],
                email: [
                    { required: false, validator: validateEmail, trigger: 'blur' }
                ],
            },
            isShowUpdateModal: false,
            columns: [
                {
                    label: '序号',
                    prop: 'index',
                    align: 'center',
                    width: 50
                },
                {
                    label: '用户姓名',
                    prop: 'userName',
                    align: 'center'
                },
                {
                    label: '用户手机号',
                    prop: 'userPhone',
                    align: 'center'
                },
                {
                    label: '用户身份证号',
                    prop: 'userIdNo',
                    align: 'center'
                },
                {
                    label: '部门名称',
                    prop: 'deptName',
                    align: 'center'
                },
                {
                    label: '用户邮箱',
                    prop: 'email',
                    align: 'center'
                },
                {
                    label: '状态',
                    prop: 'userStatus',
                    align: 'center',
                },
                {
                    label: '创建时间',
                    prop: 'createDate',
                    align: 'center'
                }
            ],
            tableList: null,
            total: 0,
            listLoading: true,
            listQuery: {
                current: 1,
                size: 20,
                userName: '',
                userPhone: ''
            },
            isShowAssignRoleModal: false,
            selectedRoleIds: [],
            currentUser: {},
            assignRoleLoading: false
        }
    },
    created() {
        this.getList();
        this.getDeptList();
        this.getRoleList();
    },
    methods: {
        // 将树形部门数据转换为扁平数组
        flattenDeptTree(deptList, level = 0) {
            let result = [];
            deptList.forEach(dept => {
                const prefix = '　'.repeat(level); // 使用全角空格作为缩进
                result.push({
                    deptId: dept.deptId,
                    deptName: prefix + dept.deptName
                });
                if (dept.children && dept.children.length > 0) {
                    result = result.concat(this.flattenDeptTree(dept.children, level + 1));
                }
            });
            return result;
        },
        handleDeptChange(value) {
            console.log('选择的部门ID:', value);
        },
        reset() {
            this.listQuery.userName = '';
            this.listQuery.userPhone = '';
            this.listQuery.current = 1;
            this.getList();
        },
        handleSearch() {
            this.listQuery.current = 1;
            this.getList();
        },
        getDeptList() {
            getDeptTree().then(res => {
                this.deptList = res;
                this.deptOptions = this.flattenDeptTree(res);
            });
        },
        getRoleList() {
            roleList().then(res => {
                this.roleOptions = res.records || res || [];
            }).catch(err => {
                console.error('获取角色列表失败:', err);
                this.$message.error('获取角色列表失败，请重试');
                this.roleOptions = [];
            });
        },
        getList() {
            this.listLoading = true;
            getAdministratorList(this.listQuery).then(res => {
                this.tableList = (res.records || []).map(user => {
                    // 处理角色信息
                    let roleNames = '';
                    if (user.roleIds) {
                        const roleIdArray = user.roleIds.split(',').map(Number);
                        roleNames = this.roleOptions
                            .filter(role => roleIdArray.includes(role.roleId))
                            .map(role => role.roleName)
                            .join(', ');
                    }

                    return {
                        ...user,
                        roleNames: roleNames || '未分配角色'
                    };
                });
                this.total = res.total;
                this.listLoading = false;
            });
        },
        handleCreate() {
            this.dialogTitle = '新增';
            this.adminForm = { ...default_form };
            this.isShowUpdateModal = true;
            // 确保表单引用存在后再重置
            this.$nextTick(() => {
                if (this.$refs.formRef) {
                    this.$refs.formRef.resetFields();
                }
            });
        },
        handleEdit(row) {
            this.dialogTitle = '编辑';
            this.adminForm = { ...row };
            this.isShowUpdateModal = true;

            // 确保所有必要字段都有值
            if (!this.adminForm.deptId) {
                this.adminForm.deptId = '';
            }
            if (!this.adminForm.email) {
                this.adminForm.email = '';
            }

            // 移除可能不存在的字段引用
            // this.adminForm.role_id = row.role_id ? row.role_id.split(',').map(Number) : [];
        },
        cancelConfirm() {
            this.isShowUpdateModal = false;
            // 确保表单引用存在后再重置
            this.$nextTick(() => {
                if (this.$refs.formRef) {
                    this.$refs.formRef.resetFields();
                }
                this.adminForm = { ...default_form };
            });
        },
        handleStatusChange(row) {
            const params = {
                id: row.id,
                userStatus: row.userStatus === 'NORMAL' ? 'DISABLE' : 'NORMAL'
            };

            updateUserStatus(params).then(res => {
                this.$message({
                    message: row.userStatus === 'NORMAL' ? '用户已启用' : '用户已禁用',
                    type: 'success'
                });
                this.getList();
            }).catch(err => {
                console.error('状态更新失败:', err);
            });
        },
        handleConfirm() {
            // 检查表单引用是否存在
            if (!this.$refs.formRef) {
                console.error('表单引用不存在');
                this.$message.error('表单初始化失败，请重试');
                return;
            }
            this.$refs.formRef.validate((res) => {
                console.log(res, '验证结果');

                if (!res) {
                    console.log('表单验证失败');
                    return;
                }

                console.log('表单验证通过，开始提交数据');

                if (this.adminForm.id) {
                    let params = {
                        id: this.adminForm.id,
                        userName: this.adminForm.userName,
                        userPhone: this.adminForm.userPhone,
                        userIdNo: this.adminForm.userIdNo,
                        deptId: this.adminForm.deptId,
                        email: this.adminForm.email
                    }
                    editAdministratorItem(params).then(res => {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        });
                        this.cancelConfirm();
                        this.getList();
                    }).catch((err) => {
                        console.error('编辑失败:', err);
                    });
                } else {
                    let params = {
                        userName: this.adminForm.userName,
                        userPhone: this.adminForm.userPhone,
                        userIdNo: this.adminForm.userIdNo,
                        password: this.adminForm.password,
                    }
                    if (this.adminForm.deptId) {
                        params.deptId = this.adminForm.deptId;
                    }
                    if (this.adminForm.email) {
                        params.email = this.adminForm.email;
                    }
                    addAdministratorItem(params).then(res => {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        });
                        this.cancelConfirm();
                        this.getList();
                    }).catch(err => {
                        console.error('新增失败:', err);
                    });
                }
            });
        },
        handleEditPassword(row) {
            console.log(row, '修改密码');
            this.isShowEditPasswordModal = true;
            this.passwordForm = { ...row };
            this.dialogTitle = '修改密码';
        },
        handleEditPasswordConfirm() {
            console.log(this.passwordForm, '修改密码');
            this.$refs.passwordFormRef.validate((res) => {
                console.log(res, '验证结果');
                if (!res) {
                    console.log('表单验证失败');
                    return;
                }
                let params = {
                    id: this.passwordForm.id,
                    oldPassword: this.passwordForm.oldPassword,
                    newPassword: this.passwordForm.newPassword
                }
                updateUserPassword(params).then(res => {
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                    this.cancelEditPasswordConfirm();
                    this.getList();
                });
            });
        },
        cancelEditPasswordConfirm() {
            this.isShowEditPasswordModal = false;
            this.passwordForm = {
                oldPassword: '',
                newPassword: ''
            };
        },
        handleAssignRole(row) {
            this.currentUser = row;
            getRoleListByUserId(row.id).then(res => {
                this.selectedRoleIds = res || [];
            })
            this.isShowAssignRoleModal = true;
        },
        cancelAssignRole() {
            this.isShowAssignRoleModal = false;
            this.selectedRoleIds = [];
            this.currentUser = {};
        },
        handleAssignRoleConfirm() {
            // 验证是否选择了角色
            if (this.selectedRoleIds.length === 0) {
                this.$message.warning('请至少选择一个角色');
                return;
            }

            this.assignRoleLoading = true;
            const params = {
                userId: this.currentUser.id,
                roleIds: this.selectedRoleIds //.join(',')
            };

            assignUserRoles(params).then(res => {
                this.$message({
                    message: '角色分配成功',
                    type: 'success'
                });
                this.cancelAssignRole();
                // 刷新角色列表和用户列表
                this.getRoleList();
                this.getList();
            }).catch(err => {
                console.error('角色分配失败:', err);
                this.$message.error('角色分配失败，请重试');
            }).finally(() => {
                this.assignRoleLoading = false;
            });
        }
    }
}
</script>

<style scoped lang="scss">
.user-container {
    padding: 20px;
}

.search-form {
    margin-bottom: 20px;
}

.dialog-footer {
    text-align: right;
}

/* 角色选择样式 */
.role-selection-container {
    min-height: 40px;

    .role-selection-container-title {
        color: #606266;
        font-size: 12px;
        margin-bottom: 10px;
    }

    .role-selection-tip {
        color: #909399;
        font-size: 12px;
        margin-top: 5px;
    }
}

.el-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.role-checkbox {
    margin-right: 0;
    margin-bottom: 10px;
    min-width: 120px;
}

/* 角色列样式 */
.role-column {
    max-width: 120px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>